<template>
	<view>
		<view class="content" :style="{ marginTop: (top * 2) + 'rpx' }">
			<view v-if="system" class="android-back"></view>
			<view v-else class="ios-back"></view>

			<view class="main-container">
				<view class="logo">
				</view>
				<view class="header-title">
				</view>
				<view class="center">
					<view class="image-card">
						<view class="photo-main-view">
							<!--  -->
							<view class="avatar-div " id="avatar-container">
								<image class="img adv-img" id="avatar-img" :src="avatarImage"></image>
								<view class="empty-view " v-if="!avatarImage">
									<view class="empty"></view>
								</view>
								<image class="avatar-default " :src="currentImage.image_url" v-if="currentImage && currentImage.image_url"></image>

							</view>
						</view>
					</view>

					<view class="ctlbtn" v-show="homeDisabled">
						<button class="action-btn btn-margin" @click="openImage('album')">

						</button>
						<button class="btn-primary btn-create" @click="toCreateAvter"></button>
					</view>
				</view>

				<view v-show="!homeDisabled">
					<view class="top-content">
						<scroll-view scroll-x :show-scrollbar="false" >
							<view class="image-div">
								<view :class="{ 'image-margin': true }" v-for="(info) in imageList" :key="info._id" @click="imageClick(info)">
									<image :src="info.image_url"></image>
								</view>
							</view>
						</scroll-view>
						<text class="more-avter"> 左滑更多周年庆头像 </text>
					</view>

					<view class="btn-container">
						<view class="btn-save" @click="shareFc()"></view>
						<view class="btn-back" @click="backHome"></view>
					</view>
				</view>

				<view class="dialog" v-if="showDialog">
					<view class="dialog-container">
						<text class="dialog-title">保存成功</text>
						<text class="dialog-main">头像已经保存到相册，一起换上北芯周年庆头像，祝北芯7周年快乐~</text>
						<button class="btn-dialog" @click="closeDialog()"></button>
					</view>
				</view>

				<view class="home-text">
				
				</view>
			</view>

			<view class="hideCanvasView">
				<canvas
					class="hideCanvas"
					id="default_PosterCanvasId"
					canvas-id="default_PosterCanvasId"
					:style="{ width: (poster.width || 10) + 'px', height: (poster.height || 10) + 'px' }"
				></canvas>
			</view>
		</view>
		<gmy-img-cropper class="cropper" ref="gmyImgCropper" cropper-type='fixed' @getImg = "getImg"></gmy-img-cropper>
	</view>
</template>

<script>
import _app from '@/util/QS-SharePoster/app.js';
import { getSharePoster } from '@/util/QS-SharePoster/QS-SharePoster.js';
import gmyImgCropper from "gmy-img-cropper/gmy-img-cropper.vue";
export default {
	components: { gmyImgCropper},
	data() {
		return {
			boderList: [],
			poster: {},
			posterImage: '',
			canvasId: 'default_PosterCanvasId',
			userInfo: '',
			code: '',
			avatarImage: uni.getStorageSync('avatar_image'),
			currentImage: {},
			currentIndex: 0,
			imageList: [],
			categoriesList: [],
			shareInfo: {},
			homeDisabled: true,
			system: true,
			showDialog: false,
			logo: '',
			sevent: '',
			top: 0
		};
	},
	onLoad() {
		this.init();
		this.getCategoriesList();
		this.getShareInfo();
	},
	onShareAppMessage: function() {
		return this.shareInfo;
	},
	onShareTimeline: function() {
		return this.shareInfo;
	},
	methods: {
		urlTobase64(fileName, format = 'png') {
   			let img = `/static/images/${fileName}.${format}`,
   			  imgBase64 = wx.getFileSystemManager().readFileSync(img, "base64"),
   			  base64Url = `data:image/png;base64,${imgBase64}`;
   			return base64Url;
		},


		judgePlatForm(){    	
			let port = uni.getSystemInfoSync().platform;
			switch (port) {
				case 'android':
					this.system = true;
					break;
				case 'ios':
					this.system = false;
					break;
				default:
					this.system = false;
					break;
			}
		},

		toCreateAvter() {
			if (!this.avatarImage) {
				uni.showToast({
					title: '需要图片才能创作喔',
					icon: 'none'
				});
				return;
			}
			this.homeDisabled = false;
		},
		backHome() {
			this.homeDisabled = !this.homeDisabled;
		},
		openImage(type){
			this.$refs.gmyImgCropper.chooseImage();
		},
		getImg:function(e){
			this.avatarImage = e;
        },
		/**
		 * 获取分享字典
		 */
		getShareInfo() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uniCloud
				.callFunction({
					name: 'code-mag',
					data: { type: 'mpweixinGet' }
				})
				.then(res => {
					if (res.result.data && res.result.data.length > 0) {
						this.shareInfo = { ...res.result.data[0], imageUrl: res.result.data[0].image_url };
						uni.setStorageSync('shareInfo', this.shareInfo);
					}
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		/**
		 * 获取分类
		 */
		getCategoriesList() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uniCloud
				.callFunction({
					name: 'categories',
					data: { type: 'mpweixin' }
				})
				.then( res => {
					this.categoriesList = res.result.data;
					console.log(res.result.data);
					if (this.categoriesList.length > 0) {
						this.$set(this.categoriesList[0], 'selected', true);
						this.getImagesList(this.categoriesList[0]._id, undefined,);
					}
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		/**
		 * @param {Object} id
		 * 获取头像
		 */
		getImagesList(id, num, imgType) {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uniCloud
				.callFunction({
					name: 'images',
					data: { type: 'mpweixin', categoryId: id }
				})
				.then(res => {
					this.imageList = res.result.data;
					if (this.imageList && this.imageList.length > 0) {
						if (num < 0) {
							this.currentImage = this.imageList[this.imageList.length - 1];
						} else {
							this.currentImage = this.imageList[0];
						}
					}
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		/**
		 * 初始化
		 */
		async init() {
			const info = uni.getMenuButtonBoundingClientRect();
			this.top = info.top + (info.height / 2);
			this.userInfo = uni.getStorageSync('user_info');
		},

		/**
		 * @param {Object} item
		 * 图片点击事件
		 */
		imageClick(item) {
			console.log('item', item);
			this.currentImage = item;
		},

		/**
		 * 获取微信code
		 */
		getWeixinCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success(res) {
						resolve(res.code);
					},
					fail(err) {
						reject(new Error('微信登录失败'));
					}
				});
			});
		},
		/**
		 * 生成新头像
		 */
		async shareFc() {
			if (!this.avatarImage) {
				uni.showToast({
					title: '请先上传图片',
					icon: 'none'
				});
				return;
			}
			try {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				_app.log('准备生成:' + new Date());
				const d = await getSharePoster({
					_this: this, //若在组件中使用 必传
					type: 'testShareType',
					formData: {
						//访问接口获取背景图携带自定义数据
					},
					backgroundImage: this.avatarImage,
					posterCanvasId: this.canvasId, //canvasId
					delayTimeScale: 20, //延时系数
					drawArray: ({ bgObj, type, bgScale }) => {
						//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
						return new Promise((rs, rj) => {
							rs([
								{
									type: 'image',
									url: this.currentImage.image_url,
									dx: 0,
									dy: 0,
									infoCallBack(imageInfo) {
										return {
											dWidth: bgObj.width, // 因为设置了圆形图片 所以要乘以2
											dHeight: bgObj.height
										};
									}
								}
							]);
						});
					},
					setCanvasWH: ({ bgObj, type, bgScale }) => {
						// 为动态设置画布宽高的方法，
						this.poster = bgObj;
					}
				});
				_app.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath);
				this.posterImage = d.poster.tempFilePath;
				this.savefile();
			} catch (e) {
				uni.hideLoading();
				_app.hideLoading();
				_app.showToast(JSON.stringify(e));
			}
		},
		/**
		 * 保存图片
		 */
		savefile() {
			//获取相册授权
			let _self = this;
			uni.getSetting({
				success(res) {
					if (!res.authSetting['scope.writePhotosAlbum']) {
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success() {
								//这里是用户同意授权后的回调
								_self.saveImgToLocal();
							},
							fail(e) {
								uni.hideLoading();
								wx.showModal({
									content: '检测到您没打开下载图片功能权限，是否去设置打开？',
									confirmText: '确认',
									cancelText: '取消',
									success: function(res) {
										//点击“确认”时打开设置页面
										if (res.confirm) {
											wx.openSetting();
										}
									}
								});
							}
						});
					} else {
						//用户已经授权过了
						_self.saveImgToLocal();
					}
				}
			});
		},
		// 关闭弹框
		closeDialog(){
			this.showDialog = false;
			this.backHome();
		},
		
		/**
		 * @param {Object} e
		 * 保存到相册
		 */
		saveImgToLocal(e) {
			let _self = this;
			uni.saveImageToPhotosAlbum({
				filePath: _self.posterImage,
				success: function() {
					uni.hideLoading();
					_self.showDialog = true;
					uni.setStorageSync('currentImage', _self.posterImage);
				},
				fail: function() {
					uni.hideLoading();
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			});
		},
	}
};
</script>

<style lang="scss" scoped>
.uni-dialog-content {
	padding: 62rpx;
}
.cropper {
	position: relative;
	z-index: 9999;
}


.dialog {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.4);
	z-index: 999;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;

	.dialog-container {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		
		padding-top: 32rpx;
		padding-left: 32rpx;
		padding-right: 32rpx;
		width: 474rpx;
		height: 260rpx;
		background: #fff;
		border-radius: 50rpx;
		font-size: 24rpx;

		.dialog-title {
			text-align: center;
			font-size: 32rpx;
			font-weight: 600;
		}
		.dialog-main {
			text-align: center;
			color: #4d4d4d94;
		}
		.btn-dialog {
			height: 70rpx;
			width: 160rpx;
			background: url('./images/comfirm.png');
			background-size: 100%;
			background-repeat: no-repeat;
		}

	}
}

.content {
	background-size: 100% 100%;
	position: relative;
	.header-title {
		width: 380rpx;
		height: 340rpx;
		background-image: $sevent_bg_base64_code;
		background-size: 100%;
		background-repeat: no-repeat;
		background-position: center;
		margin: auto;
		position: relative;
	}

	.logo {
		height: 70rpx;
		width: 160rpx;
		margin-top: 30rpx;
		margin-left: 30rpx;
		position: relative;
		z-index: 999;
		background-image: $logo_bg_base64_code;
   		background-size: cover;
	}
	.center {
		margin-top: -10rpx;
	}

	.home-text {
		width: 340rpx;
		height: 70rpx;
		background: $text_bg_base64_code;
		background-repeat: no-repeat;
		background-size: 100%;
		position: fixed;
		background-position: center;
		bottom: 0;
		left: 50%;
		transform: translate(-50%, -50%);
		// image {
		// 	width: 100%;
		// 	height: 100%;
		// }
	}

	.btn-container {
		display: flex;
		position: relative;
		z-index: 99;
		margin-top: 2rpx;

		.btn-save {
			height: 90rpx;
			width: 170rpx;
			background: url('./images/save.png');
			background-size: 100%;
			background-repeat: no-repeat;
			background-position: center;
			margin-left: 156rpx;
		}

		.btn-back {
			height: 90rpx;
			width: 170rpx;
			background: url('./images/back.png');
			background-size: 100%;
			background-repeat: no-repeat;
			background-position: center;
			margin-left: 112rpx;
		}
	}


	.android-back {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		min-height: 100vh;
		width: 750rpx;
		background-image: $android_bg_base64_code;
   		background-size: cover;
	}
	.ios-back {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		min-height: 100vh;
		width: 750rpx;
		background-image: $ios_bg_base64_code;
   		background-size: cover;
	}
	.top-content {
		width: 100%;
		background-color: #ffffff8f;
		position: relative;
		height: 230rpx;
		margin-top: 8rpx;

		.more-avter {
			position: absolute;
			top: 90%;
			left: 50%;
			transform: translate(-50%, -50%);
			font-size: 22rpx;
			color: #ff4500d1;
		}
		.top-title {
			display: flex;
			align-items: center;
			.title-unit {
				padding: 40rpx 20rpx;
				font-size: 30rpx;
			}
			.title-select {
				font-size: 30rpx;
				font-weight: bold;
				color: #ff4500;
			}
		}

		.scroll-view {
			margin-top: 10px;
		}
		.image-div {
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			padding-bottom: 20rpx;
			padding-top: 40rpx;
			image {
				width: 144rpx;
				height: 144rpx;
				border: 1rpx solid #f8f8f8;
				box-shadow: 0px -5px 15px 0px rgba(224, 224, 224, 0.4);
				flex-shrink: 0;
			}
			.image-margin {
				margin-right: 38rpx;
			}
		}
	}
	.image-card {
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		.iconfont {
			color: #f7f8fa;
			font-size: 80rpx;
			font-weight: bold;
		}
	}
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}
.success-text {
	font-size: 24rpx;
	text-align: center;
	color: #8f8f94;
}
button {
	background: 0;
 &:after {
	border: 0 !important;
 }
}
.avatar-div {
	height: 380rpx;
	margin-right: 40rpx;
	position: relative;
	width: 380rpx;
	top: 50%;
    left: 50%;
    transform: translate(-50%, 0%);
}

.avatar-div,
.empty-view {
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-webkit-box-pack: center;
	-webkit-box-align: center;
	align-items: center;
	display: flex;
	flex-direction: column;
	justify-content: center;
	z-index: 1;
}

.empty {
	height: 100px;
	margin-bottom: 24px;
	width: 100px;
	background-image: $avater_bg_base64_code;
	background-size: cover;
}

.img {
	background-color: #fff;
	border-radius: 48rpx;
	height: 360rpx;
	position: absolute;
	width: 360rpx;
	z-index: 0;
}

.avatar-default {
	border-radius: 48rpx;
	height: 100%;
	left: 0;
	position: absolute;
	top: 0;
	width: 100%;
	z-index: 10;
}

.container {
	background-color: #fbebe1;
	min-height: 100vh;
	overflow: hidden;
}
.photo-main-view {
	display: flex;
	justify-content: space-between;
	width: 404rpx;
	margin: 30rpx 30rpx 0;
}
.icon-div {
	position: relative;
	height: 80rpx;
	.icon-zuo {
		position: absolute;
		left: 0;
	}
	.icon-you {
		position: absolute;
		right: 0;
	}
}

.action-btn {
	border-radius: 48rpx;
	color: #4d4d4d;
	font-weight: bolder;
	height: 90rpx;
	line-height: 90rpx;
	font-size: 30rpx;
	padding: 0 60rpx;


	background: $get_image_bg_base64_code;
	background-size: 56%;
    background-repeat: no-repeat;
	background-position: center;
}
.btn-margin {
	margin-top: 50rpx;
}s
.btn-primary {
	background: linear-gradient(97.71deg, #ffa462, #ff4d42 88.36%);
	border: 1rpx solid #ff7852;
	border-radius: 48rpx;
	box-shadow: 0 12rpx 16rpx -8rpx rgba(255, 88, 35, 0.6);
	color: #fff;
}
.btn-create {
	margin-top: 50rpx;
	border-radius: 48rpx;
	color: #4d4d4d;
	font-weight: bolder;
	height: 90rpx;
	line-height: 90rpx;
	font-size: 30rpx;
	padding: 0 60rpx;


	background: $create_image_bg_base64_code;
	background-size: 56%;
    background-repeat: no-repeat;
	background-position: center;
}
.btn-card {
	padding: 30rpx 30rpx;
	box-sizing: border-box;
	width: 750rpx;
	.primary-btn {
		width: 330rpx;
		display: inline-block;
		margin-right: 30rpx;
		background: linear-gradient(97.71deg, #ffa462, #ff4d42 88.36%);
		border: 1rpx solid #ff7852;
		border-radius: 48rpx;
		box-shadow: 0 12rpx 16rpx -8rpx rgba(255, 88, 35, 0.6);
		color: #fff;
		padding: 0;
		font-size: 30rpx;
		height: 90rpx;
		line-height: 90rpx;
	}
	.share-btn {
		width: 330rpx;
		display: inline-block;
		background: linear-gradient(97.71deg, #ffd01e, #ff8917 60%);
		border: 1rpx solid #ff7852;
		border-radius: 48rpx;
		box-shadow: 0 12rpx 16rpx -8rpx rgba(255, 88, 35, 0.6);
		color: #fff;
		padding: 0;
		font-size: 30rpx;
		height: 90rpx;
		line-height: 90rpx;
	}
}

.hideCanvasView {
	position: relative;
}

.hideCanvas {
	position: fixed;
	top: -99999upx;
	left: -99999upx;
	z-index: -99999;
}
.popup-content {
		display:  flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
	    flex-direction: column;
	}

.popup-item{
	height: 50px;
    width: 100%;
    border-bottom: 1px solid #f8f8f8;
	display: flex;
    justify-content: center;
    align-items: center;
	}
.popup-title{
	font-size: 12px;
	color: #909399;
	height: 45px;
	width: 100%;
    border-bottom: 1px solid #f8f8f8;
	display: flex;
    justify-content: center;
    align-items: center;
}	
</style>
